﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using UFC.DBUtility;
using UFC.Common;
using System.Configuration;
using System.Data.OracleClient;
using System.Xml;

namespace MESArrangement
{
    public class SendArrangementData
    {
        public void RunArrangementSync()
        {
            //取我们系统数据
            DataTable mydt = GetArrangementNew();
            if (mydt == null || mydt.Rows.Count <= 0)
            {
              //  LogHelp.WriteLog("没有可处理的生产准备记录");
            }

            Dictionary<string, string> strList;
            //2调用其他系统的webService
            ERPService.PS_SAPServicesHttpService sap = new ERPService.PS_SAPServicesHttpService();
             //2.1 
            foreach (DataRow dr in mydt.Rows)
            {
               // LogHelp.WriteLog("处理生产准备开始" + dr["CONTAINERID"].ToString());
                strList = new Dictionary<string, string>();

                strList.Add("RQDAT", DateTime.Parse(dr["NEEDDATE"].ToString()).ToString("yyyyMMdd"));//需求日期
                strList.Add("RQTIM", "000000");//需求时间
                strList.Add("SHIFT", dr["TEAMNAME"].ToString());//班组
                strList.Add("ZUSER", dr["FULLNAME"].ToString());//使用人
                strList.Add("AUFNR", dr["MFGORDERNAME"].ToString());//生产订单号
                strList.Add("ALCNR", dr["arrangementsid2"].ToString());//派工单号 CONTAINERSTEPDISPATCHID
                if (dr["SPECNO"].ToString() == "0000")
                    strList.Add("VORNR", "0001");//工序号
                else
                    strList.Add("VORNR", dr["SPECNO"].ToString());//工序号
                if (dr["SPECNO"].ToString() == "0000")
                    strList.Add("UVORN", "0001");//子工序号
                else
                    strList.Add("UVORN", dr["PARENTSPECNO"].ToString()); //子工序号
                strList.Add("MATNR", dr["TOOLNO"].ToString());//工装工具编码
                strList.Add("MAKTX", dr["TOOLNAME"].ToString());//名称
                strList.Add("MENGE", dr["QTY"].ToString());//数量
                strList.Add("MATKL", dr["TOOLTYPE"].ToString());//工装工具类型
                strList.Add("DPSZA", dr["TOOLSTATUS"].ToString());//准备状态
                //转化成xml
                string strXML = CreateXMLForArrangement(strList);

                //

                ERPService.ErpAndAppSyncData mm = new ERPService.ErpAndAppSyncData();
                mm.ReqMsg = strXML;

                ERPService.ErpAndAppSyncDataResponse result = sap.ErpAndAppSyncData(mm);



                if (result != null)
                {
                string strMsg = "";
                strMsg = result.RespMsg;
                if (GetERPRcvXML(strMsg))//
                {
                    UpdateArrangementIntegration(dr["ARRANGEMENTSID2"].ToString());
                    OracleDAL.InsertSyncRecord(dr["ARRANGEMENTSID2"].ToString(), m_cRecordType, "成功", 0);
                }
                else
                {

                    UpdateArrangementIntegration(dr["ARRANGEMENTSID2"].ToString());
                    OracleDAL.InsertSyncRecord(dr["ARRANGEMENTSID2"].ToString(), m_cRecordType, strMsg, 1);
                }
                }
                else
                {

                }
            }

            //工装使用完成

            //辅材
        }

        /// <summary>
        /// 生产准备获取
        /// </summary>
        /// <returns></returns>
        private DataTable GetArrangement()
        {
            try
            {

                string strTmp = @"
                  SELECT CSD.CONTAINERSTEPDISPATCHID,T.QTY, T.TOOLNAME, T.TOOLNO, T.TOOLTYPE,
                  T.MFGORDERNAME,T.NEEDDATE,E.FULLNAME, T.TOOLSTATUS,S.SPECNO,S.PARENTSPECNO,
                  TE.TEAMNAME,T.ARRANGEMENTSID
                  FROM ARRANGEMENTS T
                  LEFT JOIN CONTAINERSTEPDISPATCH CSD ON CSD.CONTAINERID=T.CONTAINERID AND CSD.WORKFLOWSTEPID=T.WORKFLOWSTEPID--2017.6.5 加
                  LEFT JOIN EMPLOYEE E    ON E.EMPLOYEEID = T.EMPLOYEEID
                  LEFT JOIN WORKFLOWSTEP WFS    ON WFS.WORKFLOWSTEPID = T.WORKFLOWSTEPID
                  LEFT JOIN SPECBASE SB    ON SB.SPECBASEID = WFS.SPECBASEID
                  LEFT JOIN SPEC S    ON S.SPECID = NVL(SB.REVOFRCDID, WFS.SPECID)
                  LEFT JOIN TEAM TE    ON T.TEAMID = TE.TEAMID
                  LEFT JOIN WRITETOERPRECORD ERP
                  ON ERP.RECORDID = T.ARRANGEMENTSID
                  AND ERP.RECORDTYPE = 'arrangement'
                  WHERE T.ISINTEGRATION = 1 --AND  T.ISUSE = 0 此处无isuse字段
                  AND ERP.RECORDID IS NULL ";

                DataSet myDS = OracleHelper.Query(strTmp);
                if (myDS == null)
                {
                    return null;
                }
                if (myDS.Tables.Count == 0)
                {
                    return null;
                }
                return myDS.Tables[0];
            }
            catch (Exception e)
            {
                LogHelp.WriteError("生产准备获取", e);
                return null;
            }
        }

        /// <summary>
        /// 生产准备获取
        /// </summary>
        /// <returns></returns>
        private DataTable GetArrangementNew()
        {
            try
            {

                string strTmp = @" SELECT t.arrangementsid2,T.QTY, T.TOOLNAME, T.TOOLNO, T.TOOLTYPE,
T.MFGORDERNAME,T.NEEDDATE,E.FULLNAME, T.TOOLSTATUS,S.SPECNO,S.PARENTSPECNO,
TE.TEAMNAME
FROM ARRANGEMENTS T
LEFT JOIN EMPLOYEE E    ON E.EMPLOYEEID = T.EMPLOYEEID
LEFT JOIN WORKFLOWSTEP WFS    ON WFS.WORKFLOWSTEPID = T.WORKFLOWSTEPID
LEFT JOIN SPECBASE SB    ON SB.SPECBASEID = WFS.SPECBASEID
LEFT JOIN SPEC S    ON S.SPECID = NVL(SB.REVOFRCDID, WFS.SPECID)
LEFT JOIN TEAM TE    ON T.TEAMID = TE.TEAMID 
WHERE t.createdate>=sysdate-100 
and t.arrangementsid2 is not null 
and T.ISINTEGRATION =1 --AND  T.ISUSE = 0 此处无isuse字段                   
group by t.arrangementsid2,T.QTY, T.TOOLNAME, T.TOOLNO, T.TOOLTYPE,
T.MFGORDERNAME,T.NEEDDATE,E.FULLNAME, T.TOOLSTATUS,S.SPECNO,S.PARENTSPECNO,
TE.TEAMNAME ";

                DataSet myDS = OracleHelper.Query(strTmp);
                if (myDS == null)
                {
                    return null;
                }
                if (myDS.Tables.Count == 0)
                {
                    return null;
                }
                return myDS.Tables[0];
            }
            catch (Exception e)
            {
                LogHelp.WriteError("生产准备获取", e);
                return null;
            }
        }

        private void UpdateArrangementIntegration(string arrangementID)
        {
            string strSql = @"UPDATE ARRANGEMENTS SET ISINTEGRATION = 0
                            WHERE ARRANGEMENTSID2 = :v_recordid";

            OracleParameter[] insertParam = new OracleParameter[1];

            insertParam[0] = new OracleParameter();
            insertParam[0].ParameterName = ":v_recordid";
            insertParam[0].OracleType = OracleType.VarChar;
            insertParam[0].Direction = ParameterDirection.Input;
            insertParam[0].Value = arrangementID;

            int i = OracleHelper.ExecuteSql(strSql, insertParam);
        }

        private string CreateXMLForArrangement(Dictionary<string, string> strList)
        {

            XmlDocument doc = new XmlDocument();
            doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", ""));
            XmlNode ReqNode = doc.CreateElement("ReqMsg");
            XmlNode headerNode = doc.CreateElement("header");
            XmlNode senderNode = doc.CreateElement("sendSysName");
            senderNode.InnerText = "APP_MES";
            XmlNode rcvNode = doc.CreateElement("rcvSysName");
            rcvNode.InnerText = "APP_ERP";
            XmlNode extNode = doc.CreateElement("extConfig");
            extNode.AppendChild(doc.CreateElement("isReTry"));
            extNode.LastChild.InnerText = "false";
            extNode.AppendChild(doc.CreateElement("FunName"));
            extNode.LastChild.InnerText = "ZPPF_MES_06";
            headerNode.AppendChild(senderNode);
            headerNode.AppendChild(rcvNode);
            headerNode.AppendChild(extNode);
            ReqNode.AppendChild(headerNode);
            XmlNode documentNode = doc.CreateElement("document");
            string strData = "<ALCNRINFO>";
            foreach (KeyValuePair<string, string> _key in strList)
            {
                strData = string.Format("{0}<{1}>{2}</{1}>", strData, _key.Key, _key.Value);
            }
            strData += "</ALCNRINFO>";
            documentNode.AppendChild(doc.CreateCDataSection(strData));
            ReqNode.AppendChild(documentNode);
            doc.AppendChild(ReqNode);
            return doc.InnerXml;
        }

        /// <summary>
        /// 获取ERP反馈XML
        /// </summary>
        /// <param name="strXML"></param>
        /// <returns></returns>
        private bool GetERPRcvXML(string strXML)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(strXML);
            string isSuccess = doc.SelectSingleNode("RespMsg/header/isSuccess").InnerText;
            string meaasge = doc.SelectSingleNode("RespMsg/header/message").InnerText;

            if (isSuccess == "true" || meaasge == "S")
                return true;
            else
            {
                LogHelp.WriteLog(meaasge);
                return false;
            }
        }

        private const string m_cRecordType = "arrangement";
    }
}
